package com.fast.config;

import cn.hippo4j.config.springboot.starter.config.DynamicThreadPoolNotifyProperties;
import cn.hippo4j.config.springboot.starter.config.ExecutorProperties;
import cn.hippo4j.config.springboot.starter.config.NotifyPlatformProperties;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import java.util.HashSet;
import java.util.Set;


@Slf4j
public class JsonConvert implements ConditionalGenericConverter {

    //    private final static Class[] JSON_CLAZZ = new Class[]{NotifyPlatformProperties.class, ExecutorProperties.class};
    private final static Class[] JSON_CLAZZ = new Class[]{ExecutorProperties.class, NotifyPlatformProperties.class, DynamicThreadPoolNotifyProperties.class};

    private boolean match(Class clazz) {
        for (Class item : JSON_CLAZZ) {
            if (item.equals(clazz)) {
                return true;
            }
        }
        return false;
    }

    private Set<ConvertiblePair> generatePair() {
        Set<ConvertiblePair> set = new HashSet<>();
        for (Class clazz : JSON_CLAZZ) {
            set.add(new ConvertiblePair(String.class, clazz));
        }
        return set;
    }

    @Override
    public boolean matches(TypeDescriptor src, TypeDescriptor tar) {
        return String.class.equals(src.getObjectType()) && match(tar.getObjectType());
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return generatePair();
    }

    @Override
    public Object convert(Object source, TypeDescriptor src, TypeDescriptor tar) {
        String data = source.toString().replace("\n", "").replace("\r", "").replace("\r\n", "");
        Object after = JSONObject.parseObject(data, tar.getObjectType());
        return after;
    }
}
